package com.example.slogantv;

import android.content.Context;
import android.content.LocusId;
import android.graphics.Point;
import android.net.MacAddress;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;


import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.Utils;

import com.carlt.networklibs.NetType;
import com.carlt.networklibs.NetworkManager;

import com.carlt.networklibs.annotation.NetWork;
import com.carlt.networklibs.utils.Constants;
import com.carlt.networklibs.utils.NetworkUtils;
import com.danikula.videocache.HttpProxyCacheServer;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videoplayer.listener.OnVideoViewStateChangeListener;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.L;
import com.example.slogantv.OkHttpNetwork.HttpClientUtil;
import com.example.slogantv.OkHttpNetwork.InterfaceName;
import com.example.slogantv.OkHttpNetwork.Network;
import com.example.slogantv.asyncCallback.AsyncCallBack;
import com.example.slogantv.asyncCallback.AsyncTaskUtil;
import com.example.slogantv.base.BaseActivity;
import com.example.slogantv.base.MyApplication;

import com.example.slogantv.cache.PreloadManager;
import com.example.slogantv.cache.ProxyVideoCacheManager;
import com.example.slogantv.enity.DeviceData;
import com.example.slogantv.enity.VideoBean;
import com.example.slogantv.utlis.DataUtil;
import com.example.slogantv.utlis.DimenUtils;
import com.example.slogantv.utlis.JSONUtils;
import com.example.slogantv.utlis.MacAddressUtlis;
import com.example.slogantv.utlis.getMacUtlis;
import com.google.android.exoplayer2.RendererCapabilities;
import com.google.gson.Gson;


import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



/**
 * 连续播放一个列表
 * Created by Devlin_n on 2017/4/7.
 */
public class PlayListActivity extends BaseActivity {
    private List<VideoBean> data = DataUtil.getVideoList();
    private StandardVideoController mStandardVideoController;
    /* 定义TAG标签，这样可以很好的区分打印出来的log */
    private static final String    TAG    = "HelloAndroid";
    private ArrayList<VideoBean> videoBeans;
    private int networkNumber=0;
    private List<VideoBean> videoBeans1=new ArrayList<>();
    private boolean available;

    private Handler handler1;
    private Handler handler2;
    private int mCurrentVideoPosition=0;
    private int axxx=0;
    private int bxxx=0;
    // 状态变化监听
    /**
     * 定义一个接口
     */
    public interface   onListener{
        void OnListener(boolean networks);
    }

    /**
     *定义一个变量储存数据
     */
    private  onListener listener;

    /**
     *提供公共的方法,并且初始化接口类型的数据
     */
    public void setListener( onListener listener){
        this.listener =  listener;
    }
    //rxjava主线程处理网络请求数据
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void msgManagement(String what) {
        super.msgManagement(what);
        if (!TextUtils.isEmpty(what)){
            DeviceData deviceData = new Gson().fromJson(what, DeviceData.class);
            if (deviceData != null && deviceData.getCode() == 200) {
                List<DeviceData.DataBean.AdsBean> ads = deviceData.getData().getAds();
                if (ads != null && ads.size() > 0) {
                    List<VideoBean> videoList =new ArrayList<>();
                    for (DeviceData.DataBean.AdsBean adsBean : ads) {
                        videoList.add(new VideoBean("测试", adsBean.getShowImageUrl(), adsBean.getAdvertUrl()));
                    }
//                    集合去重取交集
                    if (data.size()>0){
                        data.clear();
                    }
//                    集合去重取交集
                    List<VideoBean> collect = videoList.stream().distinct().collect(Collectors.toList());
                    data.retainAll(collect);
                    data.addAll(videoList);
                    String s = JSONUtils.toJson(data);
                    SPUtils.getInstance().put("jsondata",s);
                    AsyncTaskUtil.doAsync(new AsyncCallBack() {
                        @Override
                        public void doInBackground() {
                            for (int i = 0; i <data.size() ; i++) {
                                PreloadManager.getInstance(getApplicationContext()).addPreloadTask(data.get(i).getUrl(), 100);
                            }
                        }
                        @Override
                        public void onPostExecute() {

                        }}); } } } }
    //  handler 异步处理，更新ui 20210908废弃
    @Override
    protected void onHandlerMessage(Message msg) {
        super.onHandlerMessage(msg);
    }
// 播放器初始化
    @Override
    protected View getContentView() {
        mVideoView = new VideoView(this);
        mVideoView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        setContentView(mVideoView);
        return mVideoView;
    }
//    网络请求数据
    private void getData() {
        Map<Object, Object> map = new HashMap<>();
//        map.put("deviceNo", "44:01:BB:E0:59:90");
        map.put("deviceNo", getMacUtlis.getMacAddress(PlayListActivity.this));
        Network.getInstance().performGet(PlayListActivity.this, map, HttpClientUtil.BASE_URL, InterfaceName.USERGETSTS, new Network.NetCallBack() {
            @Override
            public void onNetFailure() {
            }
            @Override
            public void onSuccess(JSONObject result) {
                networkNumber++;
                Log.i(TAG, "getData: 网络请求次数："+networkNumber);
//                rxjava传递
                sendMsg(result.toString());
            }
            @Override
            public void onError(String result) {
            }
        });
    }
//    是否有网络回调
   private void getnetworksdata(){
       setListener(new onListener() {
           @Override
           public void OnListener(boolean networks) {
               if (networks){
                   getData();
                   Log.i(TAG, "run: "+11111);
               }
           }
       });
   }
    @Override
    protected void initView() {
        super.initView();
        mStandardVideoController = new StandardVideoController(this);
        mStandardVideoController.setListener(networks -> {
            if (networks){
                notIntenwork();
            }
        });
        handler1 = new Handler();
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                //要做的事情
                available = NetworkUtils.isAvailable();
                if (listener!=null){
                    listener.OnListener(available);
                }
                handler1.postDelayed(this, 1000);
            }
        };
        handler1.postDelayed(runnable1, 1000);//每1秒执行一次runnable.
        getnetworksdata();
        handler2 = new Handler();
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                //要做的事情
                String jsondata = SPUtils.getInstance().getString("jsondata");
                if (!TextUtils.isEmpty(jsondata)) {
                    videoBeans1 = JSONUtils.fromJsonList(jsondata, VideoBean.class);
                    notIntenwork();
                }else {
                    notIntenwork();
                    handler2.postDelayed(this, 2000);
                } }};
        handler2.postDelayed(runnable2, 1000);//每1秒执行一次runnable.


//        }
    }
    //  添加本地缓存数据  初始化播放器 并播放
    private void notIntenwork() {
        String jsondata = SPUtils.getInstance().getString("jsondata");
        // 20210914  修改   && videoBeans1.size() > 0
        if (!TextUtils.isEmpty(jsondata) && videoBeans1.size() > 0){
            VideoBean videoBean = videoBeans1.get(0);
            HttpProxyCacheServer proxy = ProxyVideoCacheManager.getProxy(getApplication());
            String proxyUrl = proxy.getProxyUrl(videoBean.getUrl()); //设置视
            mVideoView.setUrl(proxyUrl);
            mStandardVideoController.setTitle(videoBean.getTitle());
        }
//        播放器设置控制器
        mVideoView.setVideoController(mStandardVideoController);
        //监听播放结束
        mVideoView.addOnVideoViewStateChangeListener(new OnVideoViewStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {
            }
            @Override
            public void onPlayStateChanged(int playState) {
                //视频播放完了
                if (playState == VideoView.STATE_PLAYBACK_COMPLETED) {
                    if (videoBeans1 != null&&videoBeans1.size()>0) {
                        mCurrentVideoPosition++;
                        Log.i(TAG, "onPlayStateChanged: "+mCurrentVideoPosition);
                        if (mCurrentVideoPosition >= videoBeans1.size()) mCurrentVideoPosition=0;
                        mVideoView.release();
                        //加载第一条数据
                        //重新设置数据
                        VideoBean videoBean = videoBeans1.get(mCurrentVideoPosition);
                        HttpProxyCacheServer proxy = ProxyVideoCacheManager.getProxy(getApplication());
                        String proxyUrl = proxy.getProxyUrl(videoBean.getUrl()); //设置视
                        mVideoView.setUrl(proxyUrl);
                        mStandardVideoController.setTitle(videoBean.getTitle());
                    }
                    mVideoView.setVideoController(mStandardVideoController);
                    //开始播放
                    mVideoView.start();
                }
            }
        });
        if (!TextUtils.isEmpty(jsondata) && videoBeans1.size() > 0){
            mVideoView.start();
        }

    }

    @Override
    protected int getLayoutResId() {
        return 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetworkManager.getInstance().unRegisterObserver(this);
        handler1.removeCallbacksAndMessages(null);
        handler2.removeCallbacksAndMessages(null);
    }
}
